import { Form, Modal, Input, Select, Upload, message, TreeSelect } from 'antd'
import { useForm } from 'antd/es/form/Form'
import { useEffect, useImperativeHandle, useState } from 'react'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'
import storage from '../../../utils/storage'
import type { RcFile } from 'antd/es/upload'
import type { UploadProps } from 'antd'
import { IAction, IModalProp } from '../../../types/modal'
import { Dept, Role, User } from '../../../types/api'
import api from '../../../api/api'
import roleApi from '../../../api/roleApi'
const CreateUser = (props: IModalProp) => {
  const [form] = useForm()
  const [img, setImg] = useState('')
  const [visible, setVisible] = useState(false)
  const [action, setAction] = useState<IAction>('create')
  const [loading, setLoading] = useState(false)
  const [deptList, setDeptList] = useState<Dept.DeptItem[]>([])
  const [roleList, setRoleList] = useState<Role.RoleItem[]>([])
  useEffect(() => {
    getDeptList()
    getRoleList()
  }, [])
  const getDeptList = async () => {
    const data = await api.getDeptList()
    setDeptList(data)
  }
  const getRoleList = async () => {
    const data = await roleApi.getAllRoleList()
    setRoleList(data)
  }
  //暴露子组件的open方法
  useImperativeHandle(props.mRef, () => {
    return {
      open
    }
  })
  //调用弹框显示方法
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const open = (type: IAction, data?: User.UserItem) => {
    setImg('')
    console.log('open:', data)

    setAction(type)
    setVisible(true)
    if (type === 'edit' && data) {
      form.setFieldsValue(data)
      setImg(data.userImg)
    }
  }
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!')
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!')
    }
    return isJpgOrPng && isLt2M
  }
  const handleChange: UploadProps['onChange'] = info => {
    if (info.file.status === 'uploading') {
      setLoading(true)
      return
    }
    if (info.file.status === 'done') {
      setLoading(false)
      const { code, data, msg } = info.file.response
      if (code === 0) {
        setImg(data.file)
      } else {
        message.error(msg)
      }
    } else if (info.file.status === 'error') {
      message.error('服务器异常，请稍后重试')
    }
  }
  const handleSubmit = async () => {
    const valid = await form.validateFields()
    console.log(valid)
    if (valid) {
      const params = {
        ...form.getFieldsValue(),
        userImg: img
      }
      console.log(form.getFieldsValue())
      if (action === 'create') {
        const data = await api.createUser(params)
        message.success('创建成功')

        console.log('data after create:', data)
      } else {
        const data = await api.editUser(params)
        message.success('修改成功')
        console.log('data after edit:', data)
      }
      handleCancel()
      props.update()
    }
  }
  const handleCancel = () => {
    setVisible(false)
    form.resetFields()
  }
  return (
    <Modal
      title={action === 'create' ? '创建用户' : '修改用户'}
      okText='确定'
      cancelText='取消'
      width={800}
      open={visible}
      onOk={handleSubmit}
      onCancel={handleCancel}
    >
      <Form form={form} labelCol={{ span: 4 }} labelAlign='right'>
        <Form.Item name='userId' label='用户Id' hidden>
          <Input />
        </Form.Item>
        <Form.Item
          name='userName'
          label='用户名称'
          rules={[
            { required: true, message: '请输入用户名称' },
            { min: 5, max: 12, message: '用户名称5-12个字符' }
          ]}
        >
          <Input placeholder='请输入用户名称' />
        </Form.Item>
        <Form.Item
          name='userEmail'
          label='用户邮箱'
          rules={[
            { required: true, message: '请输入用户邮箱' },
            { type: 'email', message: '请输入正确的邮箱格式' }
          ]}
        >
          <Input placeholder='请输入用户邮箱' disabled={action === 'edit'} />
        </Form.Item>
        <Form.Item
          name='mobile'
          label='手机号'
          rules={[
            {
              pattern:
                /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
              message: '请输入正确的手机号'
            }
          ]}
        >
          <Input type='number' placeholder='请输入手机号' />
        </Form.Item>
        <Form.Item name='deptId' label='部门' rules={[{ required: true, message: '请选择部门' }]}>
          <TreeSelect
            placeholder='请选择部门'
            allowClear
            treeDefaultExpandAll
            showCheckedStrategy={TreeSelect.SHOW_ALL}
            fieldNames={{ label: 'deptName', value: '_id' }}
            treeData={deptList}
          />
        </Form.Item>
        <Form.Item name='job' label='岗位'>
          <Input placeholder='请输入岗位' />
        </Form.Item>
        <Form.Item name='state' label='状态'>
          <Select>
            <Select.Option value={1}>在职</Select.Option>
            <Select.Option value={2}>离职</Select.Option>
            <Select.Option value={3}>试用期</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item name='roleList' label='角色'>
          <Select placeholder='请选择角色'>
            {roleList.map(item => {
              return (
                <Select.Option value={item._id} key={item._id}>
                  {item.roleName}
                </Select.Option>
              )
            })}
          </Select>
        </Form.Item>
        <Form.Item label='用户头像'>
          <Upload
            listType='picture-circle'
            showUploadList={false}
            headers={{
              Authorization: 'Bearer ' + storage.get('token'),
              //   icode: '7813A58290AF0FC0'
              icode: 'B815F86524423DB0'
            }}
            action='/api/users/upload'
            beforeUpload={beforeUpload}
            onChange={handleChange}
          >
            {img ? (
              <img src={img} style={{ width: '100%', borderRadius: '50%' }} />
            ) : (
              <div>
                <div>{loading ? <LoadingOutlined /> : <PlusOutlined />}</div>
                <div>头像上传</div>
              </div>
            )}
          </Upload>
        </Form.Item>
      </Form>
    </Modal>
  )
}
export default CreateUser
